package externalSort;

import java.io.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class runGenerationManager {


    public static List<String> run(String inputFileName, int generation, int totalNumbers, int bufferSize) throws IOException {
        List<String> runFiles = new ArrayList<>();

        // 使用更大的缓冲区读取文件
        try (BufferedReader reader = new BufferedReader(new FileReader(inputFileName), bufferSize)) {
            String line;
            int currentGeneration = 0;
            int runSize = getRunSize(totalNumbers, generation);

            // 持续读取直到达到指定的顺串数量或文件结束
            while (currentGeneration < generation && (line = reader.readLine()) != null) {
                List<Integer> currentRun = new ArrayList<>(runSize); // 预分配容量

                // 读取当前顺串的数据
                do {
                    if (!line.trim().isEmpty()) {
                        currentRun.add(Integer.parseInt(line.trim()));
                    }

                    // 如果达到顺串大小，就生成顺串
                    if (currentRun.size() >= runSize) {
                        break;
                    }

                } while ((line = reader.readLine()) != null);

                // 对当前顺串进行排序
                if (!currentRun.isEmpty()) {
                    Collections.sort(currentRun);

                    // 写入顺串文件
                    String runFileName = "./file/generation/run_" + currentGeneration + ".txt";
                    writeRunToFile(runFileName, currentRun,bufferSize);
                    runFiles.add(runFileName);

                    currentGeneration++;
                }
            }
        }

        System.out.println("生成顺串完成: " + runFiles.size() + " 个顺串");
        return runFiles;
    }

    /**
     * 根据顺串序号计算顺串大小
     */
    private static int getRunSize(int totalNumbers, int generations) {
        return totalNumbers / generations;
    }

    /**
     * 将顺串数据写入文件
     */
    private static void writeRunToFile(String fileName, List<Integer> runData,int bufferSize) throws IOException {
        // 确保目录存在
        File file = new File(fileName);
        file.getParentFile().mkdirs();

        try (BufferedWriter writer = new BufferedWriter(new FileWriter(fileName),bufferSize)) {
            for (Integer number : runData) {
                writer.write(number + "\n");
            }
        }
    }
}